package tcentcloudutil

import (
	"context"
	"errors"
	"github.com/cihub/seelog"
	"github.com/tencentyun/cos-go-sdk-v5"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"shop/config"
)

var cosCli = initCosClient()

func initCosClient() *cos.Client {
	// 腾讯云cos桶域名
	u, _ := url.Parse(config.Conf.TencentCloudCosDomain)
	baseUrl := &cos.BaseURL{BucketURL: u}
	return cos.NewClient(baseUrl, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  config.Conf.TencentCloudSecretId,
			SecretKey: config.Conf.TencentCloudSecretKey,
		},
	})
}

// PutObject 上传对象
// objKey: 对象键（Key）是对象在存储桶中的唯一标识。eg: test/test.txt
// 返回示例：https://xxl-1302724632.cos.ap-shanghai.myqcloud.com/test/test.txt, 空字符串表示上传失败
func PutObject(objKey string, reader io.Reader) (string, error) {
	resp, err := cosCli.Object.Put(context.Background(), objKey, reader, nil)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusOK {
		return "", errors.New("文件上传失败, " + resp.Status)
	}
	return cosCli.Object.GetObjectURL(objKey).String(), nil
}

func GetObject(key string) []byte {
	resp, err := cosCli.Object.Get(context.Background(), key, nil)
	if err != nil {
		seelog.Errorf("获取文件失败, err:%v", err)
		return nil
	}
	if resp.StatusCode != http.StatusOK {
		seelog.Warnf("获取文件失败，response:%v", resp)
		return nil
	}

	defer resp.Body.Close()
	byteArr, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		seelog.Errorf("fail to readAll from response.Body, err:%v", err)
	}
	return byteArr
}
